package com.cw.lang.common.framework.feign.codec;

import java.io.IOException;
import java.lang.reflect.Type;

import com.cw.lang.common.constants.ControllerFlagConstant;
import com.cw.lang.common.enums.EnumBool;
import com.cw.lang.common.utils.context.ThreadContextStoreUtil;

import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;

/**
 * feign decoder包装类
 *
 * @author chenw
 * @version V2.1
 * @since 2.1.0 2019-03-23 10:40
 */
@Slf4j
public class SpringDecoderWrapper implements Decoder {
    private Decoder decoder;

    public SpringDecoderWrapper(Decoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        ThreadContextStoreUtil.getInstance()
            .set(ControllerFlagConstant.FEIGN_CODEC_PROCESSING, EnumBool.YES);
        try {
            return decoder.decode(response, type);
        } finally {
            ThreadContextStoreUtil.getInstance()
                .removeKey(ControllerFlagConstant.FEIGN_CODEC_PROCESSING);
        }
    }
}
